#!/usr/bin/env ruby
#
# Bundles all files required to build for iOS in a zip archive.
#

require 'open3'
require 'tempfile'
require 'json'

version = ARGV[0] || `git describe --long --tags | cut -f 1 -d "-"`.strip

puts "Processing version: #{version}"

# Get release by tag
release = `curl -u #{ENV['GITHUB_USER']}:#{ENV['GITHUB_TOKEN']} https://api.github.com/repos/trustwallet/wallet-core/releases/tags/#{version}`
release_hash = JSON.parse(release)
upload_url = release_hash['upload_url']
puts "asset upload url: #{upload_url}"
upload_url.slice!('{?name,label}')

# First build
puts 'Building...'
_, stderr, status = Open3.capture3('tools/ios-build')
if status != 0
  STDERR.puts stderr
  exit 1
end

# Make archive
puts 'Archiving...'
includes = Dir.glob('include/**/*.h') + Dir.glob('lib/**/*.{h,hpp}')
sources = Dir.glob('swift/Sources/**/*.{swift,h,m}')
# Rename libTrustWalletCore.a to avoid conflicts with cocoapods static lib
File.rename('build/ios/libTrustWalletCore.a', 'build/ios/libCore.a')
libs = Dir.glob('build/ios/*.a')
files = includes + sources + libs + ['LICENSE']
file_name = "TrustWalletCore-iOS-#{version}.zip"
_, stderr, status = Open3.capture3('zip', file_name, *files)
if status != 0
  STDERR.puts stderr
  exit 1
end

# Upload archive
puts 'Uploading...'
upload_url = "#{upload_url}?name=#{file_name}"
puts "asset upload url: #{upload_url}"
upload_output = `curl -u #{ENV['GITHUB_USER']}:#{ENV['GITHUB_TOKEN']} -X POST -H 'Content-Type: application/octet-stream' --data-binary @#{file_name} #{upload_url}`
download_url = JSON.parse(upload_output)['browser_download_url']
puts "final download url: #{download_url}"

# Upload to Cocoapod
puts 'Publishing...'
podspec = <<-PODSPEC
Pod::Spec.new do |s|
  s.name         = 'TrustWalletCore'
  s.version      = '#{version}'
  s.summary      = 'Trust Wallet core data structures and algorithms.'
  s.homepage     = 'https://github.com/trustwallet/wallet-core'
  s.license      = 'MIT'
  s.authors      = { 'Alejandro Isaza' => 'al@isaza.ca' }
  s.module_name  = 'WalletCore'
  s.ios.deployment_target = '12.0'
  s.swift_version = '5.1'

  s.source = {
    http: "#{download_url}"
  }
  s.default_subspec = 'Core'

  s.subspec 'Types' do |ss|
    ss.source_files = 
      'swift/Sources/Types/*.swift',
      'swift/Sources/Generated/Enums/*.swift',
      'swift/Sources/Generated/Protobuf/*.swift'
    ss.dependency 'SwiftProtobuf'
  end

  s.subspec 'Core' do |ss|
    ss.preserve_paths = 'build/ios/*.a'
    ss.vendored_libraries = 'build/ios/*.a'
    ss.exclude_files = 'swift/Sources/Generated/WalletCore.h'
    ss.source_files =
      'include/**/*.h',
      'swift/Sources/*.{swift,h,m,cpp}',
      'swift/Sources/Extensions/*.swift',
      'swift/Sources/Generated/*.{swift,h}'
    ss.public_header_files =
      'include/**/*.h',
      'swift/Sources/*.h'
    ss.libraries = 'c++'
    ss.xcconfig = {
        'OTHER_LDFLAGS' => '$(inherited) -fprofile-instr-generate'
    }
    ss.pod_target_xcconfig = {
      'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64'
    }
    ss.user_target_xcconfig = { 
      'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' 
    }
    ss.dependency 'TrustWalletCore/Types'
  end
end
PODSPEC
file = File.new('build/TrustWalletCore.podspec', 'w')
file.write(podspec)
file.close

puts "Done. running 'pod trunk push --allow-warnings #{file.path}'"

stdout, stderr, status = Open3.capture3("pod trunk push --verbose --allow-warnings #{file.path}")
if status != 0
  STDERR.puts stdout
  STDERR.puts stderr
  exit 1
end
